<?php


namespace app\logic;

use think\facade\Db;

class DataHelper
{
    public static function add($table, $params) {
        $admin = get_curr_admin();
        if (!empty($admin)) {
            $params['create_dept_id'] = $admin['dept_id'];
        }

        $params['create_time'] = time_now();
        $newid = Db::table($table)->strict(false)->insertGetId($params);
        return $newid;
    }

    public static function update($table, $where, $params) {
        Db::table($table)->where($where)->strict(false)->update($params);
    }

    public static function find_by_id($table, $id) {
        return Db::table($table)->where("id=".$id)->find();
    }

    public static function find($table, $where) {
        return Db::table($table)->where($where)->find();
    }

    public static function delete($table, $where) {
        Db::table($table)->where($where)->delete();
    }

    private static function get_role_dept_condition() {
        $query = " 1=1 ";
        $admin = get_curr_admin();
        if (!empty($admin)) {
            $role = self::find_by_id('tb_role', $admin['role_id']);
            $query .= " and (create_dept_id=0 or create_dept_id in (".$role['dept_ids'].")) ";
        }

        return $query;
    }

    public static function select($table, $where, $ext = []) {
        $with_power = $ext['with_power'] ?? true;
        $order_by = $ext['order_by'] ?? 'id desc';

        $role_dept_condition = " 1=1 ";
        if ($with_power) {
            $role_dept_condition = self::get_role_dept_condition();
        }

        return Db::table($table)
            ->where($where)
            ->where($role_dept_condition)
            ->order($order_by)->select()->all();
    }

    public static function select_page($table, $where, $ext = []) {
        $with_power = $ext['with_power'] ?? true;
        $order_by = $ext['order_by'] ?? "id desc";
        $page = $ext['page'] ?? 1;
        $limit = $ext['limit'] ?? 20;

        $role_dept_condition = " 1=1 ";
        if ($with_power) {
            $role_dept_condition = self::get_role_dept_condition();
        }

        $list = Db::table($table)
            ->where($where)
            ->where($role_dept_condition)
            ->page($page)->limit($limit)->order($order_by)->select()->all();
        $count = Db::table($table)
            ->where($where)
            ->where($role_dept_condition)
            ->count();

        return [ $list, $count ];
    }

    public static function get_value($table, $where, $field) {
        $item = Db::table($table)->where($where)->find();
        return empty($item) ? '' : $item[$field];
    }

    public static function is_exist($table, $where) {
        $item = Db::table($table)->where($where)->find();
        return !empty($item);
    }
}